export default class CommonHelper {
  static log(...message: any[]) {
    console.log('[Ecommerce Helper]', ...message)
  }

  static downloadFile(
    content: string,
    filename: string,
    contentType = 'text/html'
  ) {
    // 创建a链接
    let eleLink = document.createElement('a')
    eleLink.download = filename
    eleLink.style.display = 'none'
    // 字符内容转变成BlobURL
    let blob = new Blob([content], { type: contentType })
    eleLink.href = URL.createObjectURL(blob)
    // 触发点击(开始下载)
    document.body.appendChild(eleLink)
    eleLink.click()
    // 移除标签
    setTimeout(function () {
      document.body.removeChild(eleLink)
    }, 1000)
  }

  static async saveFile(fileName: string, content: string, parentHandle?: any) {
    if (!parentHandle) {
      parentHandle = await window.showDirectoryPicker()
      if (!(await CommonHelper.verifyPermission(parentHandle))) {
        return
      }
    }
    let newFileHandle = await parentHandle.getFileHandle(fileName, {
      create: true,
    })
    // Create a FileSystemWritableFileStream to write to.
    const writable = await newFileHandle.createWritable()
    await writable.write(content)
    await writable.close()
  }

  static async saveFileFromUrl(
    fileName: string,
    url: string,
    parentHandle?: any
  ) {
    if (!parentHandle) {
      parentHandle = await window.showDirectoryPicker()
      if (!(await CommonHelper.verifyPermission(parentHandle))) {
        return
      }
    }
    let newFileHandle = await parentHandle.getFileHandle(fileName, {
      create: true,
    })
    // Create a FileSystemWritableFileStream to write to.
    const writable = await newFileHandle.createWritable()
    // Make an HTTP request for the contents.
    const response = await fetch(url)
    // Stream the response into the file.
    if (response.body) {
      return (await response.body) && response.body.pipeTo(writable)
    }
    // pipeTo() closes the destination pipe by default, no need to close it.
  }

  static async verifyPermission(fileHandle: any) {
    const options = {
      mode: 'readwrite',
    }
    // Check if permission was already granted. If so, return true.
    if ((await fileHandle.queryPermission(options)) === 'granted') {
      return true
    }
    // Request permission. If the user grants permission, return true.
    if ((await fileHandle.requestPermission(options)) === 'granted') {
      return true
    }
    // The user didn't grant permission, so return false.
    return false
  }

  static toQueryString(
    params: { [key: string]: string | number },
    prefix = '?'
  ) {
    let result = ''
    for (let key in params) {
      result += `&${key}=${params[key]}`
    }

    if (result.length > 0) {
      return (prefix ? '?' : '') + result.slice(1)
    }
    return result
  }
}
